package jude.java.money.batch.task;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jude.java.money.batch.Definition;
import jude.java.money.batch.Parameter;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

/**
 * 批量增加或修改文件
 * */
public class BatchReadTitle extends BatchTask<Object> {
	
	public BatchReadTitle(Parameter<Object> p) {
		super(p);
	}
	
	@Override
	protected void initFlags() {
		super.initFlags();
		removeFlags(Definition.CONFIG_IGNORE);
	}
	
	@Override
	protected String getLabel() {
		return "TITL";
	}
	
	protected void execute(String site, String url, int group, int index) throws IOException {
		HttpClient client = getHttpClient();
//		List<NameValuePair> params = new ArrayList<NameValuePair>();
		GetMethod method = new GetMethod("http://" + site);
		int status = client.executeMethod(method);
		if (status == 200) {
			String resp = getResponse(method, 10 * 1024);
			L.result(getTitle(resp));
		} else if (status >= 300 && status < 400) {
			Header h = method.getResponseHeader("location");
			if (h != null)
				L.result(status + " " + h.getValue());
			else
				L.result(status + " [empty]");
		} else {
			L.result(String.valueOf(status));
		}
	}
	
	private String getTitle(String html) {
		Pattern p = Pattern.compile("<title(.{10,500})</title", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(html);
		if (m.find()) {
			String title = m.group(1);
			return title.substring(title.indexOf('>') + 1);
		}
		return "[no-title]";
	}
}
